package fenyu.personblob.savepath;

import fenyu.personblob.bean.Bean;
import fenyu.personblob.error.NotFoundError;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 默认储存器
 * 模板方法
 * create at 2018/12/21 14:19
 *
 * @author 纷羽 <gzj0078@gmail.com>
 */
public class DefaultSavePath<T extends Bean> {

    private Integer id = 1;

    private HashMap<Integer, T> saver = new HashMap<Integer, T>();

    public T save(T bean) {
        if (bean.getId() == null) {
            bean.setId(id);
            saver.put(id, bean);
            id++;
        } else {
            if (saver.containsKey(bean.getId()))
                saver.put(bean.getId(), bean);
            else
                throw new NotFoundError();
        }
        return bean;
    }

    public T getById(Integer id) {
        return saver.get(id);
    }

    public List<T> getAll() {
        List<T> all = new ArrayList<T>();
        for (Map.Entry<Integer, T> entry : saver.entrySet()) {
            all.add(entry.getValue());
        }
        return all;
    }

    public T dropById(Integer id) {
        return saver.remove(id);
    }

    public boolean undoDrop(T data) {
        if (saver.containsKey(data.getId()))
            return false;
        saver.put(data.getId(), data);
        return true;
    }

}
